//
//  ViewController.swift
//  RegularExpressionDemo
//
//  Created by Jin on 2018/5/21.
//  Copyright © 2018年 Jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
       
        //let str = "fasfhghuiahgiuauallshkgiuoew"
        let str = "@coyoko:[哈哈];留接口私搭乱建看来我考虑对方回来看.@二哈:了看见阿拉山口[吃惊],@花满楼:雷克萨好几款#设么玩意#圣诞节来说[可爱]!~http://t.cn/zYBuKZB"
        
        //1.创建规则
        //let pattern = "all"  //匹配字符串 all
        //let pattern = "[a-z]"  //匹配abc...xyz
        //let pattern = "@.*?:" //匹配包含@和:,且之间有任意类型元素数量不限,若不加?会一直匹配到最后一个:
        //let pattern = "#.*?#"  //匹配话题
        //let pattern = "\\[.*?\\]"  //匹配表情
        let pattern = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"  //匹配网址
        
        /*
         [a-z]   匹配abc...xyz
         [0-9]   匹配012...789
         [a-z][0-9]或[a-z]\d 匹配第一个是字母,第二个是数字
         ^[a-z]  匹配必须第一个是字母
         ^[a-z]\d{2} 匹配必须第一个是字母且后面跟两个数字
         \d{2,10} 匹配数字由2个到10个都可以
         [a-z]$ 匹配结尾必须是字母
         ^[^0-9] 匹配首字母不能是数字
         ^[1-9]\\d{4,11}$ 匹配QQ号码
         */
        
        
        //2.创建正则表达式对象
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
            return
        }
        
        //3.匹配字符串中的内容
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.count))
        
        //4.遍历数组,获取结果
        for result in results {
            print((str as NSString).substring(with: result.range))
        }
    }


}

